import { createRouter, createWebHistory } from 'vue-router'
import ForumHome from '../views/ForumHome.vue'
import CreatePost from '../views/CreatePost.vue'
import AdminPostList from '../views/AdminPostList.vue'
import AdminStats from '../views/AdminStats.vue'
import { ref, onMounted } from 'vue'
import { getPosts, getPendingPosts, approvePost, rejectPost } from '../api/post'
import { ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '../store/user'

const routes = [
  {
    path: '/',
    name: 'ForumHome',
    component: ForumHome
  },
  {
    path: '/create-post',
    name: 'CreatePost',
    component: CreatePost
  },
  {
    path: '/admin/posts',
    name: 'AdminPostList',
    component: AdminPostList
  },
  {
    path: '/admin/stats',
    name: 'AdminStats',
    component: AdminStats
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 必须在守卫函数内部调用
  const userStore = useUserStore()
  if (to.meta && to.meta.requiresAuth && !userStore.user) {
    next('/login')
  } else {
    next()
  }
})

const activeTab = ref('all')
const posts = ref([])
const pendingPosts = ref([])

const fetchPosts = async () => {
  const res = await getPosts()
  posts.value = res.data
}
const fetchPendingPosts = async () => {
  const res = await getPendingPosts()
  pendingPosts.value = res.data
}

const approve = async (id) => {
  await approvePost(id)
  await fetchPendingPosts()
}
const reject = async (id) => {
  await rejectPost(id)
  await fetchPendingPosts()
}

onMounted(() => {
  fetchPosts()
  fetchPendingPosts()
})

export default router